package com.visionblue.business.ship.page.collection.record

import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.caysn.autoreplyprint.AutoReplyPrint
import com.caysn.autoreplyprint.AutoReplyPrint.*
import com.sun.jna.Pointer
import com.visionblue.business.ship.R
import com.visionblue.business.ship.base.BaseFragment
import com.visionblue.business.ship.base.DefaultObserver
import com.visionblue.business.ship.base.ViewState
import com.visionblue.business.ship.model.bean.local.PrintInfo
import com.visionblue.business.ship.model.bean.local.VolumeErrorInfo
import com.visionblue.business.ship.model.bean.response.ApplicationDetail
import com.visionblue.business.ship.model.enums.ApplicationTypeEnum
import com.visionblue.business.ship.model.enums.RecordMode
import com.visionblue.business.ship.model.repository.db.CollectionRecord
import com.visionblue.business.ship.page.collection.CollectionActivity
import com.visionblue.business.ship.page.collection.CollectionViewModel
import com.visionblue.business.ship.page.collection.WorkStatus
import com.visionblue.business.ship.page.dialog.CollectionConfirmDialog
import com.visionblue.business.ship.page.dialog.LoadingDialog
import com.visionblue.business.ship.page.dialog.SelectionDialog
import com.visionblue.business.ship.page.dialog.SelectionItem
import com.visionblue.business.ship.page.outer.OuterActivity
import com.visionblue.business.ship.util.ext.setVisible
import com.visionblue.business.ship.util.toast
import kotlinx.android.synthetic.main.frag_record.*
import org.koin.androidx.viewmodel.ext.android.sharedViewModel

/**
 * @author: xlh
 * @date: 2020-06-02 3:23 PM
 * @desc: 计量页面
 */
open class RecordFragment : BaseFragment() {

    protected val mAdapter = RecordAdapter()
    private val mNotRecordAdapter = NotRecordAdapter()

    protected val mViewModel: CollectionViewModel by sharedViewModel()

    //    private var flowGuideJob: Job? = null
    private var h: Pointer? = Pointer.NULL

    private val mLoadingDialog: LoadingDialog by lazy {
        LoadingDialog(context!!)
    }

    override val layoutId: Int
        get() = R.layout.frag_record

    override fun initView(savedInstanceState: Bundle?) {

        recordView.layoutManager = LinearLayoutManager(context)
        recordView.adapter = mAdapter
        mAdapter.mOnViewClickListener = object : RecordAdapter.OnViewClickListener {
            override fun onDeleteClick(record: CollectionRecord?) {
                record?.let {
                    mViewModel.deleteRecord(record)
                }
            }

            override fun onWasteTypeSelectionClick(record: CollectionRecord?,type:String): Boolean {
                var flagContain =false
                val collectionActivity:CollectionActivity = activity as CollectionActivity;
                var applicationDetail: ApplicationDetail? = collectionActivity.applicationDetail

                if(applicationDetail?.applicationItems==null){
                    if(isOutput()==true){
                        toast { "请先确定选择转出对象" }
                    }else{
                        toast { "请先确定选择接收对象" }
                    }
                }else{
                    for (data in applicationDetail?.applicationItems!!){
                        if (data.wasteType == type){
                            flagContain = true
                        }
                    }

                }

                return if (flagContain){
                    record?.wasteType = type
                    record?.let { mViewModel.updateCollectionRecord(record) }
                    true
                }else{
                    Toast.makeText(
                            activity,
                            "接收申报单不含有此项无法添加",
                            Toast.LENGTH_SHORT
                    ).show()

                    false
                }

            }
        }

        rvNotRecords.adapter = mNotRecordAdapter
        rvNotRecords.layoutManager = LinearLayoutManager(context)
        mNotRecordAdapter.onItemClickListener = object : NotRecordAdapter.OnItemClickListener {
            override fun onItemClick(type: Int) {
                SelectionDialog(context!!, listOf(
                    SelectionItem("选择处理方式", null, R.layout.title_selection_dialog),
                    SelectionItem("添加至当前任务单", {
                        mViewModel.addNotRecordToCurrent(type, isOutput())
                    }), SelectionItem("以前的任务单漏记了", {
                        mViewModel.ignoreNotRecord(type, isOutput())
                    }), SelectionItem("其他原因", {
                        mViewModel.ignoreNotRecord(type, isOutput())
                    })
                )
                ).show()
            }
        }
        addCallback()
        openPort()
    }


    var opened_callback =
        CP_OnPortOpenedEvent_Callback { handle, name, private_data ->
            activity!!.runOnUiThread {
                Toast.makeText(
                    activity,
                    "Open Success",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    var openfailed_callback =
        CP_OnPortOpenFailedEvent_Callback { handle, name, private_data ->
            activity!!.runOnUiThread {
                Toast.makeText(
                    activity,
                    "Open Failed",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    var closed_callback =
        CP_OnPortClosedEvent_Callback { h, private_data -> activity!!.runOnUiThread { closePort() } }

     fun addCallback() {
        INSTANCE.CP_Port_AddOnPortOpenedEvent(opened_callback, Pointer.NULL)
        INSTANCE.CP_Port_AddOnPortOpenFailedEvent(openfailed_callback, Pointer.NULL)
        INSTANCE.CP_Port_AddOnPortClosedEvent(closed_callback, Pointer.NULL)
    }


    //打开串口
    private fun openPort() {
        Thread(Runnable {
            h = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb("VID:0x4B43,PID:0x3538", 0)
            Log.e("--->","开串口")
            // runOnUiThread(Runnable { RefreshUI() })
        }).start()
    }

    private fun isOutput(): Boolean? {
        return when (activity) {
            is CollectionActivity -> {
                (activity as CollectionActivity).isOutput()
            }
            is OuterActivity -> {
                (activity as OuterActivity).isOutput()
            }
            else -> {
                null
            }
        }
    }

    override fun initData() {
        super.initData()

//        mViewModel.currWorkTypeLiveData.observe(this, Observer {
//            mViewModel.checkCurrWorkType(
//                currWorkType = it,
//                flow = mViewModel.checkCurrWorkStatus(
//                    beforeWork = this::showFlowBeforeWorkView,
//                    working = this::showFlowWorkingView
//                ),
//                weight = mViewModel.checkCurrWorkStatus(
//                    beforeWork = this::showWeightBeforeWorkView,
//                    working = this::showWeightWorkingView
//                )
//            )?.invoke()
//
//            mViewModel.checkCurrWorkType(currWorkType = it, flow = {
//                mViewModel.stopWatchWeightInfo()
//            }, weight = {
//                mViewModel.startWatchWeightInfo()
//            })?.invoke()
//        })

        mViewModel.getRecordsLiveData().observe(this, Observer {
            onRecordsUpdate(it)
        })

        mViewModel.workStateLiveData.observe(this, Observer {
            onWorkStateUpdate(it)
        })

        mViewModel.submitEvent.observe(
            this, DefaultObserver(loadingAction = {
                mLoadingDialog.show()
            }, finallyAction = {
                mLoadingDialog.dismiss()
            }, action = {
                onSubmitEventUpdate(it)
            })
        )

        mViewModel.volumeErrorsLiveData.observe(this, Observer {
            onVolumeErrorUpdate(it)
        })

        mViewModel.loadLocalRecords()
    }

    private fun onVolumeErrorUpdate(volumeErrorInfoSet: Set<VolumeErrorInfo>?) {
        if (volumeErrorInfoSet.isNullOrEmpty()) {
            llNotRecord.setVisible(false)
        } else {
            llNotRecord.setVisible(true)
            tvNotRecordTips.tag = true
            tvNotRecordTips.setCompoundDrawablesWithIntrinsicBounds(
                R.drawable.ic_warn,
                0,
                R.drawable.ic_pull_up,
                0
            )
            tvNotRecordTips.setOnClickListener {
                var isOpen = tvNotRecordTips.tag
                if (isOpen is Boolean) {
                    isOpen = !isOpen
                    tvNotRecordTips.tag = isOpen
                    rvNotRecords.setVisible(isOpen)
                    tvNotRecordTips.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.ic_warn, 0,
                        if (isOpen) R.drawable.ic_pull_up else R.drawable.ic_pull_down, 0
                    )
                }
            }
            mNotRecordAdapter.setData(volumeErrorInfoSet.toList())
        }
    }

    private fun onSubmitEventUpdate(it: ViewState<PrintInfo>) {
//        if (it.isLoading) {
//            MLog.e("submitEvent show... ")
//            mLoadingDialog.show()
//        } else {
//            MLog.e("submitEvent  dismiss...")
//            mLoadingDialog.dismiss()
//        }

        if (it.isSuccess) {
            val printInfo = it.data
            Log.e("---->",printInfo.toString())
            if (printInfo != null && printInfo != CollectionViewModel.EmptyPrintInfo) {
               // PrintService.start(context!!, printInfo)
                toast { "提交成功，开始打印" }
                //改变开始打印
               UsbUtil().print(activity,"Test_Label_SampleTicket_58MM_1",h,printInfo)
                /*Thread(Runnable {
                    try {
                        var testFuns = TestFunction()
                        testFuns.ctx = activity

                        var m =
                            TestFunction::class.java.getDeclaredMethod(
                               "Test_Label_SampleTicket_58MM_1",
                                Pointer::class.java
                            )
                        m.invoke(testFuns, h)
                    } catch (tr: Throwable) {
                        tr.printStackTrace()
                    }

                }).start()*/


            } else {
                toast { "提交成功" }
            }
           // activity?.finish()
        }
    }


    protected open fun onWorkStateUpdate(it: WorkStatus?) {
        when (it) {
            WorkStatus.IDLE -> showCheckAndComplete()
            WorkStatus.WORKING -> hideCheckAndComplete()
            else -> {
            }
        }
    }

    protected open fun onRecordsUpdate(records: MutableList<CollectionRecord>) {
        if (records.isEmpty()) {
            mAdapter.showEmpty()
        } else {
            mAdapter.infos = records

//            if (mViewModel.isIdle()) {
////                showCheckAndComplete()
////            } else {
////                hideCheckAndComplete()
////            }
//            mViewModel.checkCurrWorkStatus(beforeWork = {
//                showCheckAndComplete()
//            }, working = {
//
//            })?.invoke()
        }
    }

    private fun hideCheckAndComplete() {
        btnCheck.setVisible(false)
        btnComplete.setVisible(false)
    }

    private fun showCheckAndComplete() {
        btnCheck.setVisible(true)
        btnCheck.setText(R.string.check)
        btnCheck.setOnClickListener {
            mViewModel.inCheckMode.value = true
            (activity as CollectionActivity?)?.changeRecordMode(RecordMode.CHECK_MODE)
        }
        btnComplete.setVisible(true)
        btnComplete.setOnClickListener {
//            mViewModel.submitTest()
//            return@setOnClickListener
            val applicationDetail = (activity)?.findViewById<TextView>(R.id.tvMainShipName)?.tag
            if (applicationDetail == null) {
                toast { "请选择接收对象" }
                return@setOnClickListener
            }

            val toSubmitRecords = mViewModel.getRecordsLiveData().value
            toSubmitRecords?.let { list ->

                val result = mViewModel.isAllWasteTypeSelected(list)
                if (!result) {
                    toast { "存在未选择污染物类型的接收记录" }
                    return@setOnClickListener
                }

                val isOutput = when (activity) {
                    is CollectionActivity -> {
                        (activity as CollectionActivity).isOutput()
                    }
                    is OuterActivity -> {
                        (activity as OuterActivity).isOutput()
                    }
                    else -> {
                        null
                    }
                }

                CollectionConfirmDialog(
                    it.context,
                    getCollectionShipName(applicationDetail),
                    list, true, isOutput
                ).apply {
                    onDialogButtonClickListener =
                        object : CollectionConfirmDialog.OnDialogButtonClickListener {
                            override fun onSureClick(
                                isPrint: Boolean,
                                collectionRecords: List<CollectionRecord>
                            ) {
                                val detail =
                                    (activity)?.findViewById<TextView>(R.id.tvMainShipName)?.tag
                                if (detail is ApplicationDetail) {
                                    mViewModel.submit(detail, collectionRecords, isPrint)
                                }
                            }
                        }

                    show()
                }
            }
        }
    }

    private fun getCollectionShipName(applicationDetail: Any?): String? {
        if (applicationDetail is ApplicationDetail) {
            if (ApplicationTypeEnum.getApplicationType(applicationDetail.recordType) == ApplicationTypeEnum.TRANSPORT) {
                return applicationDetail.shipName
            } else {
                return applicationDetail.shipInfo?.shipName
            }
        }

        return null
    }

    //***********************************  Flow **********************
//    protected open fun showFlowBeforeWorkView() {
//        hideProgressGuide()
    // 当前为开始计量按钮
//        ivOp.visibility = View.VISIBLE
//        ivOp.setImageResource(R.drawable.ic_start_calculate)
//        ivOp.setOnClickListener {
//            hideProgressGuide()
//            SelectionDialog(
//                it.context, listOf(
//                    SelectionItem("含油污水", {
//                        mViewModel.flowType.value = FlowType.OIL
//                        mViewModel.currWorkStatusLiveData.value = WorkStatus.WORKING
//                        showFlowWorkingView()
//                        mViewModel.createLocalOilRecord()
//                    }),
//                    SelectionItem("生活污水", {
//                        mViewModel.currWorkStatusLiveData.value = WorkStatus.WORKING
//                        mViewModel.flowType.value = FlowType.WATER
//                        showFlowWorkingView()
//                        mViewModel.createLocalWaterRecord()
//                    })
//                )
//            ).show()
//        }

//        flowGuideJob?.cancel()
//        flowGuideJob = launch {
//            delay(15000)
//            showProgressFlowGuide()
//        }

//    }


//    private fun showFlowWorkingView() {

//        flowGuideJob?.cancel()
//        hideProgressGuide()
//
//        btnCheck.visibility = View.INVISIBLE
//        btnComplete.visibility = View.INVISIBLE
//        // 当前为停止计量按钮
//        ivOp.visibility = View.VISIBLE
//        ivOp.setImageResource(R.drawable.ic_stop_calculate)
//        ivOp.setOnClickListener {
//            mViewModel.currWorkStatusLiveData.value = WorkStatus.BEFORE_WORK
//            mViewModel.insertFlowRecord()
//            showFlowBeforeWorkView()
//        }

//    }


    // *******************  weight *******************************

//    protected open fun showWeightBeforeWorkView() {
//        flowGuideJob?.cancel()
//        hideProgressGuide()
//        ivOp.visibility = View.VISIBLE
//        ivOp.setImageResource(R.drawable.ic_start_weigh)
//        ivOp.setOnClickListener {
//            hideProgressGuide()
//            SelectionDialog(it.context, listOf(SelectionItem("固废垃圾", {
////                mViewModel.currWorkStatusLiveData.value = WorkStatus.WORKING
//                mViewModel.recordWeight()
////                mViewModel.currWorkStatusLiveData.value = WorkStatus.BEFORE_WORK
//            }))).show()
//        }

//        mViewModel.isShowProgressWeightGuide.observe(this, Observer {
//            if (it) {
//                showProgressWeightGuide()
//            } else {
//                hideProgressGuide()
//            }
//        })

//        mViewModel.checkShowWeightGuide()
//    }


//    private fun showWeightWorkingView() {
//        showWeightBeforeWorkView()
//    }

//    private fun showProgressWeightGuide() {
//        tvGuideText.visibility = View.VISIBLE
//        ivHand.visibility = View.VISIBLE
//        tvGuideText.text = "点击记录\n当前称重\n读数"
//    }

//    private fun showProgressFlowGuide() {
//        tvGuideText.visibility = View.VISIBLE
//        ivHand.visibility = View.VISIBLE
//        tvGuideText.text = "点击开始\n记录流量\n计读数"
//    }

//    private fun hideProgressGuide() {
//        tvGuideText.visibility = View.GONE
//        ivHand.visibility = View.GONE
//    }

    companion object {
        fun newInstance(): RecordFragment {
            return RecordFragment()
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        closePort()
    }

    private fun closePort() {
        if (h !== Pointer.NULL) {
            AutoReplyPrint.INSTANCE.CP_Port_Close(h)
            h = Pointer.NULL
        }
    }
}